angular.module('invoice-apply',[])

.controller 'invoiceApplyCtrl', ($scope,showToast,$http,$ionicPopup,$state,userData,$ionicHistory) ->
    loadData=()->
        $http.get '/accounts',params:{action:'getinvoicemoney',userid:userData.getToken()}
        .success (resp) ->
            if resp.status == '0'
                $scope.balance=Number(resp.allmoney) if Number(resp.allmoney)>=0
        .error (err)->
            console.log err
    $scope.$on '$ionicView.enter',->
        $scope.balance=''
        $scope.invData={
            subject:''
            fundamount:''
            purpose:''
            address:''
            postcode:''
            receiver:''
            telephone:''
        }
        loadData()
    _.extend $scope,
        goBack: ->
            $ionicHistory.goBack()
        goRecord:->
            $state.go 'tab.invoice-record'
        checkAmount:()->
            reg=/^([1-9][\d]{0,8}[\.]?[\d]{0,2})$/;
            money=$scope.invData.fundamount
            console.log $scope.invData.fundamount
            if money=='' or money==undefined
                money=''
            else if reg.test(money)
                angular.noop
            else
                money=money.substr(0,money.length-1)
            $scope.invData.fundamount=money
        checkForm:()->
            data=$scope.invData
            if data.fundamount==''
                showToast '发票金额不能为空'
                return false
#            if Number(data.cashmoney)>Number($scope.balance)
#                showToast '发票金额不能大于可开金额'
#                return false
            if Number(data.cashmoney)<100
                showToast '发票金额不能低于100元'
                return false
            if data.address=='' or data.subject=='' or data.purpose=='' or data.postcode=='' or data.receiver=='' or data.telephone==''
                showToast '所有信息皆为必填项'
            return true
        submit:()->
            if !$scope.checkForm()
                return
            $scope.invData.action='supplyinvoice'
            $scope.invData.userid=userData.getToken()
            $http.post '/utf-8data/',$scope.invData
            .success (resp) ->
                console.log resp
                if resp.status =='0'
                    $ionicPopup.alert({
                        title:'申请成功'
                        okText:'确定'
                    })
                    $scope.invData={
                        subject:''
                        fundamount:''
                        purpose:''
                        address:''
                        postcode:''
                        receiver:''
                        telephone:''
                    }
                else
                    showToast resp.msg
            .error (err) ->
                showToast '网络连接不稳定!'